package com.uzhie.util;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by TangFei on 2018/8/11.
 * 缓存管理
 */
public class CacheManager<K, V> {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private org.springframework.cache.ehcache.EhCacheCacheManager ehCacheCacheManager;

    private net.sf.ehcache.CacheManager cacheManager;

    @PostConstruct
    protected void init() {
        cacheManager = ehCacheCacheManager.getCacheManager();
    }

    public enum DES {

        SYS_CACHE("SYSCache"), PLA_SESSION_CACHE("PlaSessionCache"), JT808_SESSION_CACHE("JT808SessionCache"), MEDIA_SESSION_CACHE("MediaSessionCache");

        String name;

        DES(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    public void put(DES des, K key, V value) {
        Cache cache = ehCacheCacheManager.getCache(des.getName());
        cache.put(key, value);
    }

    public V get(DES des, K key, Class<V> valueClass) {
        Cache mediaCache = ehCacheCacheManager.getCache(des.getName());
        try {
            V value = mediaCache.get(key, valueClass);
            return value;
        } catch (IllegalStateException e) {
            return null;
        }
    }

    /**
     * 获取所有 key
     *
     * @param des
     * @return
     */
    public List<K> getKeys(DES des) {
        return cacheManager.getCache(des.getName()).getKeys();
    }

    public void remove(DES des, K key) {
        Cache cache = ehCacheCacheManager.getCache(des.getName());
        cache.evict(key);
    }

}
